<template>
  <s-layout
    :title="page.name"
    navbar="custom"
    :tabbar="currentPagePath"
    :bgStyle="page.style?.background"
    :navbarStyle="page.style?.navbar"
    onShareAppMessage
    showLeftButton
  >
    <s-block v-for="(item, index) in page.list" :key="index" :styles="item.style">
      <s-block-item :type="item.type" :data="item.data" :styles="item.style" />
    </s-block>
  </s-layout>
</template>

<script setup>
  import { computed, reactive, ref } from 'vue';
  import sheep from '@/sheep';
  import { onLoad, onPageScroll, onShow } from '@dcloudio/uni-app';
  import { showAuthModal } from '@/sheep/hooks/useModal';

  const page = reactive({
    name: '',
    list: [],
    style: {},
  });
  
  const pageId = ref('');
  const isLogin = computed(() => sheep.$store('user').isLogin);
  
  // 动态计算当前页面路径
  const currentPagePath = computed(() => {
    // 只有在显示底部导航且有页面ID时才返回路径
    if (pageId.value) {
      const fullPath = `/pages/index/page?id=${pageId.value}`;
      
      // 检查底部导航配置中是否有匹配的项
      const tabbar = sheep.$store('app').template?.basic?.tabbar;
      if (tabbar?.list) {
        // 查找匹配的导航项
        const matchedItem = tabbar.list.find(item => {
          // 检查是否完全匹配（包含参数）
          if (item.url === fullPath) return true;
          
          // 检查基础路径是否匹配
          const itemBasePath = item.url.split('?')[0];
          const currentBasePath = fullPath.split('?')[0];
          if (itemBasePath === currentBasePath) return true;
          
          // 检查是否是带有相同ID参数的页面
          if (item.url.startsWith(`/pages/index/page?id=${pageId.value}`)) return true;
          
          return false;
        });
        
        // 如果找到匹配项，返回基础路径用于激活
        if (matchedItem) {
          return fullPath.split('?')[0]; // 返回不含查询参数的基础路径
        }
      }
      
      return fullPath;
    }
    
    return '';
  });
  onLoad(async (options) => {
    let id;

    if (options.id) {
      id = options.id;
      pageId.value = id; // 设置页面ID
    }

    // #ifdef MP
    // 小程序预览自定义页面
    if (options.scene) {
      const sceneParams = decodeURIComponent(options.scene).split('=');
      id = sceneParams[1];
      pageId.value = id; // 设置页面ID
    }
    // #endif

    const { code, data } = await sheep.$api.app.page(id);
    if (code === 1) {
      page.name = data.name;
      page.list = data.diypage?.page?.data;
      page.style = data.diypage?.page?.style;
    }
  });

  onShow(() => {
    // 未登录时直接显示登录弹框
    if (!isLogin.value) {
      showAuthModal('accountLogin');
    }
  });

  onPageScroll(() => {});
</script>

<style></style>
